'use strict';
const db = uniCloud.database();
const dbCmd = db.command;

/**
 * 诊断用户的佣金计算
 * 查询用户的所有推广订单，计算佣金应该是多少
 */
exports.main = async (event, context) => {
    const { userId } = event;
    
    if (!userId) {
        return { code: 400, message: '请提供 userId' };
    }
    
    console.log(`\n========== 开始诊断用户 ${userId} 的佣金 ==========\n`);
    
    try {
        // 1. 获取用户信息
        const userRes = await db.collection('users').doc(userId).get();
        if (userRes.data.length === 0) {
            return { code: 404, message: '用户不存在' };
        }
        
        const user = userRes.data[0];
        console.log('【用户信息】');
        console.log(`  用户ID: ${user._id}`);
        console.log(`  昵称: ${user.nickname}`);
        console.log(`  当前待激活佣金: ${user.commission_pending} 分 (¥${(user.commission_pending / 100).toFixed(2)})`);
        console.log(`  当前可提现佣金: ${user.commission_available} 分 (¥${(user.commission_available / 100).toFixed(2)})`);
        console.log(`  累计收益: ${user.commission_total} 分 (¥${(user.commission_total / 100).toFixed(2)})`);
        
        // 2. 获取佣金配置
        const settingsRes = await db.collection('settings').where({ key: 'default' }).get();
        const settings = settingsRes.data[0] || {};
        const commissionRate = settings.rules?.commission?.purchaseRebate || 0.1;
        console.log(`\n【佣金配置】`);
        console.log(`  佣金比例: ${(commissionRate * 100).toFixed(1)}%`);
        
        // 3. 获取用户的所有推广订单
        const ordersRes = await db.collection('orders')
            .where({ promoter_id: userId })
            .orderBy('create_time', 'desc')
            .get();
        
        console.log(`\n【推广订单统计】`);
        console.log(`  总订单数: ${ordersRes.data.length}`);
        
        // 按状态分类
        const ordersByStatus = {};
        let totalOrderAmount = 0;
        let totalCommission = 0;
        let pendingCommission = 0;
        let activatedCommission = 0;
        
        for (const order of ordersRes.data) {
            const status = order.status;
            if (!ordersByStatus[status]) {
                ordersByStatus[status] = { count: 0, amount: 0, commission: 0 };
            }
            ordersByStatus[status].count++;
            ordersByStatus[status].amount += order.amount || 0;
            ordersByStatus[status].commission += order.commission_amount || 0;
            
            totalOrderAmount += order.amount || 0;
            totalCommission += order.commission_amount || 0;
            
            if (order.commission_status === 'pending') {
                pendingCommission += order.commission_amount || 0;
            } else if (order.commission_status === 'activated') {
                activatedCommission += order.commission_amount || 0;
            }
        }
        
        console.log(`  订单总金额: ${totalOrderAmount} 分 (¥${(totalOrderAmount / 100).toFixed(2)})`);
        console.log(`  应得佣金总额: ${totalCommission} 分 (¥${(totalCommission / 100).toFixed(2)})`);
        console.log(`  待激活佣金: ${pendingCommission} 分 (¥${(pendingCommission / 100).toFixed(2)})`);
        console.log(`  已激活佣金: ${activatedCommission} 分 (¥${(activatedCommission / 100).toFixed(2)})`);
        
        console.log(`\n【按订单状态分类】`);
        for (const [status, data] of Object.entries(ordersByStatus)) {
            console.log(`  ${status}: ${data.count} 笔，金额 ¥${(data.amount / 100).toFixed(2)}，佣金 ¥${(data.commission / 100).toFixed(2)}`);
        }
        
        // 4. 对账
        console.log(`\n【对账结果】`);
        const discrepancy = totalCommission - (user.commission_pending + user.commission_available);
        console.log(`  应得佣金: ¥${(totalCommission / 100).toFixed(2)}`);
        console.log(`  实际佣金: ¥${((user.commission_pending + user.commission_available) / 100).toFixed(2)}`);
        console.log(`  差异: ¥${(discrepancy / 100).toFixed(2)}`);
        
        if (discrepancy === 0) {
            console.log(`  ✅ 对账无误`);
        } else if (discrepancy > 0) {
            console.log(`  ❌ 缺少 ¥${(discrepancy / 100).toFixed(2)} 的佣金`);
        } else {
            console.log(`  ⚠️ 多出 ¥${(Math.abs(discrepancy) / 100).toFixed(2)} 的佣金`);
        }
        
        return {
            code: 0,
            data: {
                user: {
                    id: user._id,
                    nickname: user.nickname,
                    commission_pending: user.commission_pending,
                    commission_available: user.commission_available,
                    commission_total: user.commission_total
                },
                config: {
                    commissionRate: commissionRate
                },
                orders: {
                    total: ordersRes.data.length,
                    totalAmount: totalOrderAmount,
                    totalCommission: totalCommission,
                    pendingCommission: pendingCommission,
                    activatedCommission: activatedCommission,
                    byStatus: ordersByStatus
                },
                reconciliation: {
                    shouldBe: totalCommission,
                    actual: user.commission_pending + user.commission_available,
                    discrepancy: discrepancy
                }
            }
        };
    } catch (err) {
        console.error('诊断失败:', err.message);
        return { code: 500, message: `诊断失败: ${err.message}` };
    }
};

